<template>
  <div class="container">
    <div class="search">
<!--      请假查询年份：-->
      <el-form size="mini" :inline="true">
        <el-form-item label="请选择查询条件：">
          <el-date-picker
              v-model="year"
              value-format="yyyy"
              type="year"
              placeholder="选择年"
              @change="changeYear"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-date-picker
              v-model="month"
              format="M"
              value-format="M"
              type="month"
              placeholder="选择月"
              @change="changeMonth"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input v-if="isCheck" v-model="deptName" :disabled="isCheck"></el-input>
<!--          <el-select v-if="isAdmin" v-model="params.dept_id" placeholder="请选择">-->
<!--            <el-option-->
<!--                v-for="item in depList"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item.id"-->
<!--            >-->
<!--            </el-option>-->
<!--          </el-select>-->
          <el-cascader
              v-if="isAdmin"
              style="width: 450px"
              clearable
              placeholder="请选择"
              v-model="dept_id"
              :options="options"
              :props="{ expandTrigger: 'hover',label:'name',value:'id',children:'children',checkStrictly:true }"
              @change="handleChange">
          </el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" style="margin-left: 1em" type="info" @click="select">
            查询
          </el-button>
          <el-button size="mini" style="margin-left: 1em" type="primary" @click="exportExcel">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table
          id="out-table"
          ref="table"
          size="mini"
          stripe
          :data="tableData"
          align="center"
          height="90%"
          highlight-current-row
          style="width: 100%">
        <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="username"
            label="人力编码"
            align="center"
            width="150">
        </el-table-column>
        <el-table-column
            prop="name"
            label="员工姓名"
            align="center"
            width="150">
        </el-table-column>
        <el-table-column
            prop="persontype"
            label="人员类别"
            align="center"
            width="150">
        </el-table-column>
        <el-table-column
            prop="role"
            label="人员职位"
            align="center"
            width="150">
        </el-table-column>
        <el-table-column
            prop="post"
            label="人员角色"
            align="center"
            width="150">
        </el-table-column>
        <el-table-column
            prop="dept_4j"
            label="四级单元"
            align="center"
            width="150">
        </el-table-column>
        <el-table-column
            prop="dept_3j"
            label="三级单元"
            align="center"
            width="150">
        </el-table-column>
        <el-table-column
            v-for="item in List"
            :label="item.day"
            :key="item.day"
            align="center"
        >
          <el-table-column
              :prop="item.prop_am"
              label="上午"
              align="center"
              width="120">
          </el-table-column>
          <el-table-column
              :prop="item.prop_pm"
              label="下午"
              align="center"
              width="120">
          </el-table-column>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleSizeChange"
            :current-page.sync="pagination.currentPage"
            :page-size="pagination.pageSize"
            :page-sizes="pagination.pageSizes"
            background
            layout="total,sizes ,prev, pager, next,jumper"
            :total="pagination.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {holidayCountByDept} from "@/utils/statistic";
import {deptList} from "@/utils/dept";
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'

export default {
  name: "Charts",
  data(){
    return {
      user:JSON.parse(localStorage.getItem('user') || '{}'),
      year:'',
      month:'',
      dept_id: [],
      params:{
        year:0,
        month:0,
        dept_id: 0
      },
      options:[],
      depList:[],
      isAdmin:false,
      isCheck:false,
      deptName:'',
      List:[],
      tableData:[],
      pagination:{
        currentPage:1,
        pageSizes:[5,10,15,20,50,100,200,500,1000],
        pageSize:15,
        total:100
      },
      total:0
    }
  },
  created() {
    this.init()
  },
  mounted() {

  },
  methods:{
    handleChange(val){
      console.log("val=========",val)
      // this.params.dept_id = this.dept_id[this.dept_id.length -1]
      this.dept_id = val
      this.params.dept_id = val[val.length-1]
    },
    init(){
      let myDate = new Date()
      this.year = myDate.getFullYear()+''
      this.month = myDate.getMonth()+''
      deptList({}).then(res=>{
        if(res.code===1){
          this.depList = res.data
          this.options = res.data
          const node = this.findNodeById(res.data, this.user.dept_id);
          this.params.dept_id = node.id
          console.log("this.dept_id==========",this.dept_id)
        }
      })
      if(this.user.role === '管理员'){
        this.isAdmin = true
      }else if(this.user.role === '考勤员'){
        this.isCheck = true
      }
      this.deptName = this.user.dept
      this.changeProp(parseInt(this.year,10),parseInt(this.month,10))
      this.getList()
    },
   getMonthDays(year,month){
      let startDate = new Date(year,month-1,1)
      let endData = new Date(year,month,1);
      let days = (endData -startDate)/(1000*60*60*24);
      return days;
  },
    changeProp(year,month){
      this.List = []
      let length=this.getMonthDays(year,month)
      console.log('length',length)
      for(let i=1;i<=length;i++){
        this.List.push({
          // day:i+'',
          // prop_am:'date_'+i+'_am',
          // prop_pm:'date_'+i+'_pm'
          day:this.year+'-'+this.judgeMonth(this.month)+'-'+this.judgeMonth(i),
          // prop_am:this.year+'-'+this.judgeMonth(this.month)+'-'+this.judgeMonth(i)+'_上午',
          // prop_pm:this.year+'-'+this.judgeMonth(this.month)+'-'+this.judgeMonth(i)+'_下午',
          prop_am:this.year+this.judgeMonth(this.month)+this.judgeMonth(i)+'_上午',
          prop_pm:this.year+this.judgeMonth(this.month)+this.judgeMonth(i)+'_下午',
        })
      }
    },
    judgeMonth(month){
      if(parseInt(month,10)<10){
        month = '0'+month
      }
      return month
    },
    changeYear(){
      this.changeProp(parseInt(this.year,10),parseInt(this.month,10))
      this.getList()
    },
    changeMonth(){
      this.changeProp(parseInt(this.year,10),parseInt(this.month,10))
      this.getList()
    },
    select(){
      this.getList()
      console.log(this.params)
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.getList()
    },
    handleSizeChange(pageSize){
      this.pagination.pageSize = pageSize
      this.getList()
    },
    async getList(){
      this.tableData = []
      this.params.year = parseInt(this.year,10)
      this.params.month = parseInt(this.month,10)
      let params = {
        ...this.params,
        page_number:this.pagination.currentPage,
        page_size:this.pagination.pageSize
      }
      await holidayCountByDept(params).then(res=>{
        if(res.code==='1'){
          this.$message.success(res.message)
          for(let i=0;i<res.data.length;i++){
            let dayTemp = this.getMonthDays(parseInt(this.year,10),parseInt(this.month,10))
            if('dept_4j' in res.data[i] && res.data[i].dept_4j === null){
              res.data[i].dept_4j = '无'
            }
            for(let j=1;j<=dayTemp;j++){
              let attributeAm = this.year+this.judgeMonth(this.month)+this.judgeMonth(j)+'_上午'
              let attributePm = this.year+this.judgeMonth(this.month)+this.judgeMonth(j)+'_下午'
              if(attributeAm in res.data[i] && res.data[i][attributeAm] === null){
                res.data[i][attributeAm] = '/'
              }
              if(attributePm in res.data[i] && res.data[i][attributePm] === null){
                res.data[i][attributePm] = '/'
              }
            }
          }
          this.tableData = res.data
          this.pagination.total = res.page_total
          this.total = res.page_total //导出使用
          this.pagination.currentPage = res.page_number
          this.pagination.pageSize = res.page_size
        }else{
          this.$message.error(res.message)
          this.pagination.total = 0
          this.pagination.currentPage = 1
          this.pagination.pageSize = 15
        }
      })
    },
    async getListAll(){
      this.tableData = []
      this.params.year = parseInt(this.year,10)
      this.params.month = parseInt(this.month,10)
      let params = {
        ...this.params,
        page_number:1,
        page_size:this.total
      }
      await holidayCountByDept(params).then(res=>{
        if(res.code==='1'){
          this.$message.success(res.message)
          for(let i=0;i<res.data.length;i++){
            let dayTemp = this.getMonthDays(parseInt(this.year,10),parseInt(this.month,10))
            if('dept_4j' in res.data[i] && res.data[i].dept_4j === null){
              res.data[i].dept_4j = '无'
            }
            for(let j=1;j<=dayTemp;j++){
              let attributeAm = this.year+this.judgeMonth(this.month)+this.judgeMonth(j)+'_上午'
              let attributePm = this.year+this.judgeMonth(this.month)+this.judgeMonth(j)+'_下午'
              if(attributeAm in res.data[i] && res.data[i][attributeAm] === null){
                res.data[i][attributeAm] = '/'
              }
              if(attributePm in res.data[i] && res.data[i][attributePm] === null){
                res.data[i][attributePm] = '/'
              }
            }
          }
          this.tableData = res.data
          this.pagination.total = res.page_total
          this.total = res.page_total //导出使用
          this.pagination.currentPage = res.page_number
          this.pagination.pageSize = res.page_size
        }else{
          this.$message.error(res.message)
          this.pagination.total = 0
          this.pagination.currentPage = 1
          this.pagination.pageSize = 15
        }
      })
    },
    async exportExcel(){
      await this.getListAll()
      this.exportCurrentExcel()
    },
    exportCurrentExcel(){
      var xlsxParam = {raw:true}
      var wb = XLSX.utils.table_to_book(
          document.querySelector("#out-table"),
          xlsxParam
      );
      var wbout = XLSX.write(wb,{
        bookType:"xlsx",
        bookSST:true,
        type:"array"
      })
      const node = this.findNodeById(this.depList, this.dept_id[this.dept_id.length - 1]);
      try{
        FileSaver.saveAs(
            new Blob([wbout],{type:"application/octet-stream"}),
            `${this.year+'-'+this.judgeMonth(this.month)+'-请假记录-'+node.name}.xlsx`
        );
      }catch (e){
        if(typeof console !== "undefined"){
          console.log(e,wbout)
        }
      }
      return wbout;
    },
    findNodeById(nodes, id) {
      for (let node of nodes) {
        if (node.id === id) {
          this.dept_id.push(node.id)
          return node;
        }
        if (node.children && node.children.length > 0) {
          this.dept_id.push(node.id)
          // eslint-disable-next-line no-undef
          const foundNode = this.findNodeById(node.children, id);
          if (foundNode) {
            return foundNode;
          }
        }
      }
        return null;
}
  }
}
</script>

<style lang="less" scoped>
.container{
  width: 100%;
  height: 100%;
  .table{
    margin-top: 20px;
    position: relative;
    height: 90%;
    .block{
      position: absolute;
      bottom: 0;
      right: 20px;
    }
  }
}
.el-cascader-panel .el-radio{
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 10px;
  right: 10px;
}
.el-cascader-panel .el-radio__input{
  visibility: hidden;
}
.el-cascader-panel .el-cascader-node__postfix {
  top: 10px;
}
</style>
